package com.movisol.messenger.views;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
import android.widget.ViewAnimator;

import com.movisol.c2dm.events.RegistrationIdReceivedEvent;
import com.movisol.c2dm.helpers.C2DMHelper;
import com.movisol.c2dm.ilisteners.IRegistrationIdReceived;
import com.movisol.messenger.R;
import com.movisol.messenger.controllers.MessengerController;
import com.movisol.messenger.helper.MessengerHelper;
import com.movisol.messenger.views.controls.EmailTab;
import com.movisol.messenger.views.controls.LoadingTab;
import com.movisol.messengerprofileservice.asynctasks.AsyncSubscribePushNotification;
import com.movisol.messengerprofileservice.data.UserProfile;
import com.movisol.messengerprofileservice.events.DataLoadedEvent;
import com.movisol.messengerprofileservice.events.PushNotificationSubscribedEvent;
import com.movisol.messengerprofileservice.helpers.MessengerProfileHelper;
import com.movisol.messengerprofileservice.listeners.IPushNotificationSubscribed;
import com.movisol.messengerprofileservice.listeners.IUserProfileDataLoadedListener;
import com.movisol.tools.HelperUtils;


/**
 * Login page that allows the user to Sign In to the application 
 * @author Antonio Santiago
 */
public class Login extends Activity implements IUserProfileDataLoadedListener, OnClickListener, IRegistrationIdReceived, IPushNotificationSubscribed{
	
	private final MessengerController mc = MessengerController.getInstance();
	
	private Context context;
	
	private final static int EXIT_RESULT_CODE = -1;

	private String email;
	private ViewAnimator viewAnim;
	private LoadingTab loadingTab;
	private EmailTab emailTab;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		context = mc.getContext();
		getWindow().setFormat(PixelFormat.RGBA_8888);
		getWindow().addFlags(LayoutParams.FLAG_DITHER);
		
		if(!mc.isLoaded())
		{
			mc.initialize();
			mc.pc.addUserProfileDataLoadedListener(this);
			mc.pc.addPushNotificationSubscribedListener(this);
			mc.c2dmc.addRegistrationListener(this);
			
		}
		
		initializeGUI();
		
		email = MessengerHelper.getSavedEmail(context);
		
		//If an email is found to be active, do the login
		if(email != null && !email.trim().equals(""))
		{
			mc.getUserProfile(email);
		}
		else //Show the Sign In form
		{
			viewAnim.addView(emailTab);
			viewAnim.showNext();			
		}
		
	}
	

	
	/**
	 * Initialize all the GUI components, images, buttons, etc 
	 */
	private void initializeGUI() {
		
		//TODO load images
			
		viewAnim = (ViewAnimator) findViewById(R.id.viewAnimlogin);
		
		loadingTab = new LoadingTab(context);

		viewAnim.addView(loadingTab);
		
		emailTab = new EmailTab(context, "Sign In", null);
		emailTab.getBtOkEmail().setOnClickListener(this);
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if ((keyCode == KeyEvent.KEYCODE_BACK))
			setResult(EXIT_RESULT_CODE);

		return super.onKeyDown(keyCode, event);
	}
		

	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
	}


	/**
	 * If no error has occurred, saves the email and show the next page
	 * @param evt Event Object containing the information about errors
	 * */
	@Override
	public void userProfileDataLoaded(DataLoadedEvent evt) {
		
		if(evt.getError() == null)
		{
			MessengerHelper.saveEmail(context, email);
			//Let`s go back to the Main Page			
			mc.pc.removeUserProfileDataLoadedListener(this);
						
			// Call to Google to get the registration id just in case the
			// registrationId is expired
			if (C2DMHelper.isRegistrationIdExpired(context))
				mc.getRegistrationId(this);
			
			mc.setLoaded(true);
			mc.pc.setConversationUriCacheFileName(mc.pc.getUserProfile().getUserId());
			finish();
		}
		else
		{
			//The email account is not associated with this device
			//It sends an email to verify the email account
			if(mc.pc.getUserProfile().isEmailVerified() == null)
			{
				mc.pc.getUserProfile().setEmailVerified(false);
				mc.getUserProfile(email);
			}
			else
			{
				//Once the email have been sent, exits the app
				//showing the necessary message
				setResult(EXIT_RESULT_CODE);
				HelperUtils.LogE(evt.getSource().getClass(), evt.getError());
				HelperUtils.showToastMessage(context, evt.getError(), Toast.LENGTH_LONG);
				
				
				new AsyncTask<Void, Void, Void>() {
					
					@Override
					protected Void doInBackground(Void... params) {
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						super.onPostExecute(result);
						finish();
					}
					
				}.execute();
			}
		}
	}



	@Override
	public void onClick(View v) {
		switch(v.getId())
		{
			case R.id.btOkEmail:
					email = emailTab.getEdTxtEmail().getText().toString();
					
					if(MessengerProfileHelper.validateEmail(email))
					{
						emailTab.hideErrorMessage();
						viewAnim.showPrevious();
						if(mc.pc.getUserProfile() == null)
							mc.pc.setUserProfile(new UserProfile());
						
						mc.pc.getUserProfile().setEmailVerified(false);
						mc.getUserProfile(email);
					}
					else
					{
						emailTab.showErrorMessage("Invalid Email");
					}
			break;
			
		
		}
		
	}

	@Override
	public void registrationIdReceived(RegistrationIdReceivedEvent evt)
	{
		mc.isNetWorkAvailable(new AsyncSubscribePushNotification());
	}

	@Override
	public void pushNotificationSubscribed(PushNotificationSubscribedEvent evt) {
		//TODO ver que se quiere hacer con la respuesta del servidor
		
	}

}
